<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='utf-8'>
    <meta content='IE=edge' http-equiv='X-UA-Compatible'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>websocket</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <style>
        .panel-body {
            min-height: 200px;
            max-height: 400px;
            overflow: auto;
        }

        .label {
            padding: 0.3em .5em .5em;
        }

        html,body {
            font: 12px/1 "Microsoft Yahei", "微软雅黑", "黑体", "SimHei", Arial,sans-serif;
            color: #2E2E2E;
            height: 100%;
        }
        .panel-body::-webkit-scrollbar{height:8px;width:8px;background:rgba(152, 152, 152, 0.3);border-radius:5px;}
        .panel-body::-webkit-scrollbar-button{display:none;}
        .panel-body::-webkit-scrollbar-track{background-color:#ffffff;}
        .panel-body::-webkit-scrollbar-track-piece{background:#ffffff;}
        .panel-body::-webkit-scrollbar-thumb{width:8px;min-height:15px;background:rgba(0, 0, 0, 0.2);border-radius:5px;}
        .panel-body::-webkit-scrollbar-thumb:hover{background:rgba(0, 0, 0, 0.6);}
        .panel-body::-webkit-scrollbar-thumb:active{background:rgba(0, 0, 0, 0.8);}
        p {
            padding-bottom: 10px;
        }
        .alert {
            padding: 9px;
            text-align: center;
        }
        .container {
            max-width: 670px;
        }
    </style>
</head>
<body>
<div class="container">

    <div class="page-header">
        <h1>
            websocket
            <small>websocket for thinkphp</small>
        </h1>
    </div>
    <div class="panel panel-default">
        <div class="panel-body">

        </div>
    </div>
    <div class="form-group has-success has-feedback">
        <label class="control-label" for="message">请文明发言,勿刷屏,按回车键发送消息</label>
        <input type="text" class="form-control" id="message" placeholder="输入你想对大家说的话">
    </div>
</div>
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
    var FancyWebSocket = function(url)
    {
        var callbacks = {};
        var ws_url = url;
        var conn;

        this.bind = function(event_name, callback){
            callbacks[event_name] = callbacks[event_name] || [];
            callbacks[event_name].push(callback);
            return this;// chainable
        };

        this.send = function(event_name, event_data){
            if(this.conn.readyState === 3){
                return false;
            }
            this.conn.send( event_data );
            return this;
        };

        this.connect = function() {
            if ( typeof(MozWebSocket) == 'function' )
                this.conn = new MozWebSocket(url);
            else
                this.conn = new WebSocket(url);

            // dispatch to the right handlers
            this.conn.onmessage = function(evt){
                dispatch('message', evt.data);
            };

            this.conn.onclose = function(){dispatch('close',null)}
            this.conn.onopen = function(){dispatch('open',null)}
        };

        this.disconnect = function() {
            this.conn.close();
        };

        var dispatch = function(event_name, message){
            var chain = callbacks[event_name];
            if(typeof chain == 'undefined') return; // no callbacks for this event
            for(var i = 0; i < chain.length; i++){
                chain[i]( message )
            }
        }
    };

</script>
<script>
    var Server;
    $(function(){
        log('连接中...', 'info');
        Server = new FancyWebSocket('ws://127.0.0.1:9300');

        Server.bind('open', function() {
            log( "连接成功.", 'success');
        });
        Server.bind('close', function( data ) {
            log( "已经断开.", 'danger');
        });
        Server.bind('message', function( payload ) {
            addMessage(payload, 'left', 'primary');
        });

        Server.connect();

        // 绑定消息框
        $('#message').keypress(function(e) {
            if ( e.keyCode == 13 && this.value ) {
                addMessage($(this).val(), 'right');
                if(Server.send( 'message', $(this).val()) === false){
                    log('没有连接服务器!', 'danger');
                };
                $(this).val('');
            }
        });
    })


    // 将消息上屏
    function addMessage(msg, x, y){
        if(!y){
            y="success";
        }

        $('<p class="text-' + x + '">\
                   <span class="label label-' + y + '">' + msg + '</span>\
              </p>').appendTo('.panel-body');

        $log = $('.panel-body');
        $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
    }
    function log(msg, x){
        if(!x){
            x="success";
        }
        $('<div class="alert alert-' + x + '" role="alert">' + msg + '</div>').appendTo('.panel-body')
        $log = $('.panel-body');
        $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
    }



</script>
</body>
</html>